package com.aaa.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * Spring Security配置类
 */
    //当前类是个配置类
    @Configuration
    //使用security配置
    @EnableWebSecurity
    //启用权限注解配置
    @EnableGlobalMethodSecurity(securedEnabled = true,jsr250Enabled = true,prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    UserDetailsServiceImpl userDetailsService;

    @Resource
    SuccessHandler successHandler;

    @Resource
    FailureHandler failureHandler;

    @Resource
    DeniedHandler deniedHandler;

    @Resource
    EntryPointHandler entryPointHandler;

    @Resource
    JwtAuthenticationFilter jwtAuthenticationFilter;


    /**
     * 1.是否登录
     * 2.认证
     *      a.验证用户身份是否正确；
     */

    /**
     * http请求处理配置
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http)throws Exception{
        http
                .authorizeRequests()
                .antMatchers("/css/**","/js/**","/img/**")
                .permitAll()
                .and()
                //授权请求
                //.authorizeRequests()
                //所有请求
                //.anyRequest()
                //已认证
                //.authenticated()//所有请求必须经过身份认证（登录）之后才能授权访问
                //.and()
                //配置form表单进行登录
                .formLogin()
                //登录页面
                .loginPage("/index.html")
                //用户名参数：security默认表单提交时用户名叫username
                .usernameParameter("eusername")
                //密码参数：security默认表单提交时密码叫password
                .passwordParameter("epassword")
                //登录验证路径：form表单的提交路径，默认提交路径/login
                .loginProcessingUrl("/login-check")
                //默认成功路径
                //.defaultSuccessUrl("/main.html")    //   /user/success
                //失败访问路径
                //.failureUrl("/user/error")

                .successHandler(successHandler)
                .failureHandler(failureHandler)

                //允许访问
                .permitAll()
                .and()
                .authorizeRequests()
                .anyRequest()
                //允许访问判断：调用方法，使用方法的返回结果做判断，判断是否可以访问
                //.access("@rabcConfig.hasPermission(authentication,request)")
                .authenticated()
                .and()

                //异常处理器
                .exceptionHandling()
                //访问被拒绝
                .accessDeniedHandler(deniedHandler)
                .authenticationEntryPoint(entryPointHandler)
                .and()
                //运行cors请求
                .cors()
                .and()
                //跨域请求
                .csrf()
                //启用
                .disable();
        // 在security判断是否认证之前，先拦截请求，判断是否携带token
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }


    /**
     * 认证配置
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web)throws Exception{
        web.ignoring().antMatchers();
    }
}
